<template>
  <div>
    <PageWrapper :contentFullHeight="true">
      <Row :gutter="24">
        <Col :xs="24" :sm="24" :md="24" :lg="4" :xl="4">
          <!-- 目录区 -->
          <div class="tree-container">
            <BasicTree
              :treeData="catalogData"
              :toolbar="true"
              :search="true"
              @select="handleSelect"
            />
          </div>
        </Col>
        <!-- 发布图档区 -->
        <Col :xs="24" :sm="24" :md="24" :lg="20" :xl="20" style="background-color: white">
          <Row>
            <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <BasicTable
                @register="registerTable"
                :searchInfo="searchInfo"
                @row-click="handleRowClick"
              >
                <!-- 创建时间 -->
                <template #createTime="{ text: createTime }">
                  <span>
                    {{ proxy.$filters.filterTime(createTime) }}
                  </span>
                </template>
                <!-- 截止时间 -->
                <template #lookDeadTime="{ text: lookDeadTime }">
                  <span>
                    {{ proxy.$filters.filterTime(lookDeadTime) }}
                  </span>
                </template>
                <!-- 发布时间 -->
                <template #releaseTime="{ text: releaseTime }">
                  <span>
                    {{ proxy.$filters.filterTime(releaseTime) }}
                  </span>
                </template>
                <!-- 文档状态 -->
                <template #status="{ text: status }">
                  <span>
                    <Tag :color="status === '8' ? 'green' : status === '1' ? 'red' : 'blue'">
                      {{ proxy.$filters.filterDocumentStatus(status) }}
                    </Tag>
                  </span>
                </template>
                <!-- 生命周期 -->
                <template #lifecycle="{ text: lifecycle }">
                  <span>
                    <Tag
                      :color="lifecycle === '0' ? 'green' : lifecycle === '128' ? 'red' : 'blue'"
                    >
                      {{ proxy.$filters.filterLifeCycleStatus(lifecycle) }}
                    </Tag>
                  </span>
                </template>
                <!-- 操作 -->
                <template #action="{ record }">
                  <TableAction
                    :actions="[
                      {
                        label: t('common.preview'),
                        onClick: handleBrowse.bind(null, record),
                      },
                      {
                        label: t('common.download'),
                        onClick: handleDownload.bind(null, record),
                      },
                      {
                        label: t('common.print'),
                        onClick: handlePrint.bind(null, record),
                      },
                      {
                        label: t('routes.table.documentReleaseArea.ReleaseList.releaseAgain'),
                        onClick: handleReRelease.bind(null, record),
                        ifShow: false,
                      },
                      {
                        label: t('routes.table.documentReleaseArea.ReleaseList.revokeDocument'),
                        onClick: handleRevoke.bind(null, record),
                      },
                    ]"
                  />
                </template>
              </BasicTable>
            </Col>
          </Row>
          <Divider />
          <Row>
            <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <Tabs v-model:activeKey="detailActiveKey">
                <TabPane key="version" :tab="t('routes.table.documentReleaseArea.historyVersion')">
                  <BasicTable @register="registerHistory" :searchInfo="searchHistory">
                    <!-- 创建时间 -->
                    <template #status="{ text: status }">
                      <span>
                        <Tag :color="status === '8' ? 'green' : status === '1' ? 'red' : 'blue'">
                          {{ proxy.$filters.filterDocumentStatus(status) }}
                        </Tag>
                      </span>
                    </template>
                    <!-- 创建时间 -->
                    <template #createtime="{ text: createtime }">
                      <span>
                        {{ proxy.$filters.filterTime(createtime) }}
                      </span>
                    </template>
                  </BasicTable>
                </TabPane>
                <TabPane key="log" :tab="t('routes.table.documentReleaseArea.operationLog')">
                  <BasicTable @register="registerLog" :searchInfo="searchLog">
                    <!-- 时间 -->
                    <template #bitime="{ text: bitime }">
                      <span>
                        {{ proxy.$filters.filterTime(bitime) }}
                      </span>
                    </template>
                  </BasicTable>
                </TabPane>
              </Tabs>
            </Col>
          </Row>
        </Col>
      </Row>
      <!-- 回收文档 -->
      <RetrieveDoc @register="registerRetrieveDocModal" @success="reloadTable()" />
    </PageWrapper>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, getCurrentInstance } from 'vue';
  import { Row, Col, Divider, Tabs, TabPane, Tag } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTree } from '/@/components/Tree/index';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { useUserStore } from '/@/store/modules/user';

  import throttle from 'lodash/throttle';
  import printJS from 'print-js';

  import {
    getReleaseColumns,
    getReleaseConfig,
    getHistoryColumns,
    getLogColumns,
  } from './tableData';

  import {
    getDirectoryLevel,
    GetPdmObjReleases,
    GetReleaseFileVersion,
    GetOpreationAct,
    downloadFile,
    printFile,
  } from '/@/api/demo/document';

  import RetrieveDoc from './RetrieveDoc.vue';
  import { handleBrowseFile } from '/@/utils/demo/preview';

  const { proxy }: any = getCurrentInstance();
  const { createMessage } = useMessage();
  const useCommonStore = useUserStore();
  const { t } = useI18n();
  // 目录数据源
  const catalogData = ref<any>([]);
  // 文档详情
  const detailActiveKey = ref('version'); // 版本version， 日志 log
  // 发布文档搜索条件
  const searchInfo = ref<any>({
    IdOrName: '', // 代号/文件名
    fUserId: '', // 发布人
    sUserId: '', // 接受人
    releaseTime: '', // 开始时间
    endTime: '', // 截止时间
    folderId: '', // 目录ID
  });

  // 历史版本搜索条件
  const searchHistory = ref<any>({
    folderId: '', // 目录ID
  });
  // 操作日志搜索条件
  const searchLog = ref<any>({
    folderId: '', // 目录ID
  });

  onMounted(() => {
    getCatalog();
  });

  // 获取目录方法
  const getCatalog = async () => {
    const res = await getDirectoryLevel(0);
    catalogData.value = res;
  };

  // 目录树选中事件
  const handleSelect = (selectedKeys: any) => {
    searchInfo.value.folderId = selectedKeys[0];
    reloadTable();
    // 清空历史版本和操作日志
    setHistoryData([]);
    setLogData([]);
  };

  // 当前行点击
  const handleRowClick = async (record: any) => {
    const versionList = await GetReleaseFileVersion(record.oid); // 获取版本信息
    const logList = await GetOpreationAct(record.oid); // 获取日志信息
    setHistoryData(versionList);
    setLogData(logList);
  };

  // 浏览
  const handleBrowse = async (record: Recordable) => {
    await handleBrowseFile(record, '发布区');
  };

  // 下载
  const handleDownload = throttle((record: Recordable) => {
    downloadFile(record.oid, record.docVersion, record.filename).then(() => {
      createMessage.success(t('common.downLoadSuccess'));
    });
  }, 3000);

  // 打印
  const handlePrint = (record: any) => {
    printFile(record.oid, record.docVersion).then((res) => {
      if (
        res.suffix == 'pdf' ||
        res.suffix == 'jpg' ||
        res.suffix == 'jpeg' ||
        res.suffix == 'png'
      ) {
        printJS({ printable: res.binaryStream, type: 'pdf', base64: true });
      } else {
        createMessage.error(t('routes.table.documentReleaseArea.ReleaseList.notSupportPrint'));
      }
    });
  };

  // 二次发布
  const handleReRelease = (record: any) => {
    console.log('二次发布', record);
  };

  // 收回图档
  const handleRevoke = (record: any) => {
    openRevokeModal(true, record);
  };

  // 表格初始化
  const [registerTable, { reload: reloadTable }] = useTable({
    titleHelpMessage: 'releaseIndex',
    columns: getReleaseColumns(), // 表格列配置
    api: GetPdmObjReleases, // 表格数据请求方法
    bordered: true,
    useSearchForm: true,
    formConfig: getReleaseConfig(), // 表单配置
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: false,
    maxHeight: 220,
    actionColumn: {
      width: 300,
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 历史版本表格初始化
  const [registerHistory, { setTableData: setHistoryData }] = useTable({
    titleHelpMessage: 'releaseVersion',
    columns: getHistoryColumns(), // 表格列配置
    bordered: true,
    showIndexColumn: false,
    showTableSetting: false, // 显示表格设置工具
    pagination: false,
    maxHeight: 220,
  });

  // 操作日志表格初始化
  const [registerLog, { setTableData: setLogData }] = useTable({
    titleHelpMessage: 'releaseLog',
    columns: getLogColumns(), // 表格列配置
    bordered: true,
    showIndexColumn: false,
    showTableSetting: false, // 显示表格设置工具
    pagination: false,
    maxHeight: 220,
  });

  // 回收文档弹窗
  const [registerRetrieveDocModal, { openModal: openRevokeModal }] = useModal();
</script>

<style lang="less" scoped>
  ::v-deep(.ant-calendar-picker) {
    width: 100% !important;
  }

  .tree-container {
    height: 90vh;
    overflow-y: auto;
    background-color: white;
  }
</style>
